import os
import tkinter as tk
from tkinter import ttk, scrolledtext, Toplevel, PhotoImage, CENTER, Label, BOTH
from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
import io
import windnd
from zsm import *  # 假设赞赏图片数据在此模块

# 在文件顶部添加字体注册
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 注册Windows中文字体（黑体）
try:
    pdfmetrics.registerFont(TTFont('SimHei', r'C:\Windows\Fonts\simhei.ttf'))
except:
    # 备用字体路径尝试
    pdfmetrics.registerFont(TTFont('SimHei', r'C:\Windows\Fonts\simhei.ttf'))
class PDFWatermarkTool:
    def __init__(self, root):
        self.root = root
        self.root.title("PDF批量文字水印工具       By:风二西  2025.03.03")
        self.root.geometry("500x200")

        # 简洁配置区
        config_frame = ttk.Frame(root)
        config_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Label(config_frame, text="水印文字:").pack(side=tk.LEFT)
        self.watermark_text = ttk.Entry(config_frame, width=20)
        self.watermark_text.pack(side=tk.LEFT, padx=5)
        self.watermark_text.insert(0, "风二西")

        # 底部操作栏
        bottom_frame = ttk.Frame(root)
        bottom_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=5)
        ttk.Button(bottom_frame, text="赞赏作者", command=self.donate_author).pack(side=tk.LEFT)
        ttk.Label(bottom_frame, text="更多工具欢迎关注bilibili风二西").pack(side=tk.RIGHT)

        # 消息输出框
        self.msg_text = scrolledtext.ScrolledText(root, height=10, wrap=tk.WORD,
                                                  state='disabled', bg="Ivory")
        self.msg_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 拖放支持
        windnd.hook_dropfiles(self.root, func=self.handle_drop)

        # 标签样式
        self.msg_text.tag_config('success', foreground='darkgreen')
        self.msg_text.tag_config('error', foreground='red')

    def create_watermark(self):
        """生成包含三个水印的PDF页面"""
        packet = io.BytesIO()
        c = canvas.Canvas(packet, pagesize=A4)
        c.setFillAlpha(0.3)  # 固定透明度

        # 设置中文字体（使用注册的字体名称）
        try:
            c.setFont("SimHei", 36)  # 首选黑体
        except:
            c.setFont("Helvetica", 36)  # 备用字体
            self.log_message("警告：中文字体加载失败，使用默认字体", 'error')

        text = self.watermark_text.get()

        # 三个水印位置
        positions = [
            (300, 200, 45),  # 左下方
            (300, 400, 45),  # 中间,  # 中间
            (300, 600, 45),  # 右上方

        ]

        for x, y, angle in positions:
            c.saveState()
            c.translate(x, y)
            c.rotate(angle)
            c.drawCentredString(0, 0, text)
            c.restoreState()

        c.save()
        packet.seek(0)
        return PdfReader(packet).pages[0]

    def donate_author(self):
        """赞赏作者窗口"""
        self.zsm_windows = Toplevel(self.root)
        self.zsm_windows.wm_attributes("-topmost", 1)
        self.zsm_windows.title('赞赏作者')
        self.photo1 = PhotoImage(data=zsm123)  # 确保zsm模块包含图片数据
        self.zsm1 = Label(self.zsm_windows, image=self.photo1, compound=CENTER)
        self.zsm1.pack(fill=BOTH, expand=True)

    # 保留其他原有方法（process_pdf、handle_drop等，需删除文件选择相关代码）
    def handle_drop(self, files):
        paths = [f.decode('gbk') for f in files]
        self.process_files(paths)

    def process_files(self, file_paths):
        valid_files = [f for f in file_paths if f.lower().endswith('.pdf')]
        if not valid_files:
            self.log_message("错误：未找到PDF文件", 'error')
            return

        for pdf_file in valid_files:
            self.process_pdf(pdf_file)

    def process_pdf(self, pdf_path):
        try:
            watermark_page = self.create_watermark()
            output_path = pdf_path.replace('.pdf', '_水印版.pdf')

            reader = PdfReader(pdf_path)
            writer = PdfWriter()

            for page in reader.pages:
                page.merge_page(watermark_page)
                writer.add_page(page)

            with open(output_path, "wb") as out_file:
                writer.write(out_file)

            self.log_message(f"成功处理：{os.path.basename(pdf_path)}", 'success')
        except Exception as e:
            self.log_message(f"处理失败：{os.path.basename(pdf_path)} - {str(e)}", 'error')

    def log_message(self, message, msg_type='info'):
        self.msg_text.configure(state='normal')
        self.msg_text.insert(tk.END, message + '\n', msg_type)
        self.msg_text.see(tk.END)
        self.msg_text.configure(state='disabled')
        self.root.update_idletasks()


if __name__ == "__main__":
    root = tk.Tk()
    app = PDFWatermarkTool(root)
    root.mainloop()
